package com.asiainfo.exec.core;

import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class SpringTaskApplication extends SpringApplication {

    private static String[] springArgs;

    private static String[] taskArgs;

    private static String taskName;

    private static boolean argsParsed;

    public static synchronized ConfigurableApplicationContext run(Class<?> primarySource, String... originArgs) {
        argsParsed = false;

        CmdLineParser springArgsParser = new CmdLineParser("---");
        springArgsParser.doParser(originArgs);
        String[] args0 = springArgsParser.getArgs();
        springArgs = convertToSpringArgs(args0);


        CmdLineParser taskArgsParser = new CmdLineParser("-", "--");
        taskArgsParser.doParser(originArgs);
        String[] args1 = taskArgsParser.getArgs();
        taskArgs = preParseTaskArgs(args1);

        argsParsed = true;
        return run(new Class<?>[]{primarySource}, springArgs);
    }

    private static String[] preParseTaskArgs(String... args) {
        List<Object> res = new ArrayList<>();
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-task")) {
                i++;
                taskName = args[i];
            } else {
                res.add(arg);
            }
        }
        return res.toArray(new String[res.size()]);
    }

    private static String[] convertToSpringArgs(String... args) {
        for (int i = 0; i < args.length; i++) {
            if (!StringUtils.isEmpty(args[i])) {
                args[i] = args[i].replaceAll("^---(.*)$", "--$1");
            }
        }
        return args;
    }

    public final static String[] getSpringArgs() {
        Assert.isTrue(argsParsed, "Unresolved parser");
        return springArgs;
    }

    public final static String[] getTaskArgs() {
        Assert.isTrue(argsParsed, "Unresolved parser");
        return taskArgs;
    }

    public static String getTaskName() {
        Assert.isTrue(argsParsed, "Unresolved parser");
        return taskName;
    }
}
